<?php
/**
 * Created by PhpStorm.
 * User: jungshen
 * Date: 2019/2/26
 * Time: 11:01
 */

namespace app\api2\controller\member;


use app\api\controller\BasicUserApi;
use app\api\service\MemberService;
use service\DataService;
use think\Db;

/**
 * 找人控制器
 * Class RecruitWorker
 * @package app\api2\controller\member
 */
class RecruitWorker extends BasicUserApi
{
    /**
     * 发布找人信息
     * @return \think\response\Json
     */
    function release(){
        if($this->request->isPost()){
            /**
             * //worker_info json数据可解析出下面这种格式
             * worker_info[0]['type']//工种
             * worker_info[0]['number']//人数
             * worker_info[0]['price']//工价/天
             */
            $post=$this->request->only(
                ['start_time','end_time',
                    'grab_sheet_end_time',//抢单结束时间
                    'address','image',//image 多个用|隔开
                    'desc','is_overtime','overtime_fee','pay_type','life_ids','worker_info','voice']
                ,'post');
            //处理数据
            $post['start_time']=strtotime($post['start_time']);
            $post['end_time']=strtotime($post['end_time']);
            $post['grab_sheet_end_time']=strtotime($post['grab_sheet_end_time']);
            if($post['is_overtime']&&$post['overtime_fee']=='')$post['overtime_fee']='面议';
            $worker_info=json_decode($post['worker_info'],true);
            foreach ($worker_info as $k=>&$v){
                if($v['type']<1||$v['number']<1){
                    return json(['msg'=>'工人信息有误'],500);
                }
                if($v['price']==''){
                    $v['price']='面议';
                }
            }
            $post['worker_info']=json_encode($worker_info);
            $post['mid']=UID;
            $post['status']=0;
            $post['addtime']=time();
            $post['order_sn']=DataService::createSequence(10,'RECRUITWORKER');
            Db::name('recruit_worker')
                ->insert($post);
            return json(['msg'=>'发布成功,请等待审核'],200);
        }
    }

    /**
     * 找人列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function lists(){
        $page_size=$this->request->get('page_size',10);
        $page_now=$this->request->get('page_now',1);
        $list=Db::name('recruit_worker')
            ->where('mid','<>',UID)
            ->where('status',1)
            ->field('id,mid,desc,addtime,grab_sheet_end_time,image,status')
            ->page($page_now,$page_size)
            ->order('id desc')
            ->select();
        foreach ($list as $k=>&$v){
            $v['addtime']=date('Y/m/d',$v['addtime']);
            $v['grab_sheet_end_time']=date('Y/m/d H',$v['grab_sheet_end_time']);
            $v['image_arr']=explode('|',$v['image']);
        }
        return json(['msg'=>'success','data'=>$list],200);
    }

    /**
     * 我发布的找人列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function mine(){
        $page_size=$this->request->get('page_size',10);
        $page_now=$this->request->get('page_now',1);
        $list=Db::name('recruit_worker')
            ->field('id,desc,addtime,grab_sheet_end_time,image,status')
            ->where('mid',UID)
            ->page($page_now,$page_size)
            ->order('id desc')
            ->select();
        foreach ($list as $k=>&$v){
            $v['addtime']=date('Y/m/d',$v['addtime']);
            $v['grab_sheet_end_time']=date('Y/m/d H',$v['grab_sheet_end_time']);
            $v['image_arr']=explode('|',$v['image']);
            //查询抢单的工人
            $v['grab_sheet']=Db::name('recruit_worker_grab_sheet')
                ->alias('gs')
                ->join('worker_info wi','wi.mid=gs.mid')
                ->join('store_member m','m.id=wi.mid')
                ->where('gs.recruit_worker_id',$v['id'])
                ->field('wi.name,wi.work_type_ids,m.phone,gs.id')
                ->select();
            foreach ($v['grab_sheet'] as &$gsv){
                //TODO::只查询需求的工种 $tmp=array_intersect(explode(',',$gsv['work_type_ids']),explode(',',$v['work_type_ids']))
                $gsv['work_type_arr']=Db::name('my_cate')->where('id','in',$gsv['work_type_ids'])->column('title');
            }
        }
        return json(['msg'=>'success','data'=>$list],200);
    }

    /**
     * 我的抢单列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function my_grab_sheet(){
        $page_size=$this->request->get('page_size',10);
        $page_now=$this->request->get('page_now',1);
        $list=Db::name('recruit_worker_grab_sheet')
            ->alias('gs')
            ->join('recruit_worker rw','rw.id=gs.recruit_worker_id')
            ->join('store_member m','m.id=rw.mid')
            ->field('rw.id,rw.desc,rw.addtime,rw.grab_sheet_end_time,rw.image,rw.status rw_status,m.nickname,m.phone,gs.status')
            ->where('gs.mid',UID)
            ->page($page_now,$page_size)
            ->select();
        foreach ($list as $k=>&$v){
            $v['addtime']=date('Y/m/d',$v['addtime']);
            $v['grab_sheet_end_time']=date('Y/m/d H',$v['grab_sheet_end_time']);
            $v['image_arr']=explode('|',$v['image']);
        }
        return json(['msg'=>'success','data'=>$list],200);
    }

    /**
     * 抢单
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    function grab_sheet(){
        //招工记录ID
        $recruit_worker_id=$this->request->get('recruit_worker_id');
        //查询找工人信息
        $recruit_worker=Db::name('recruit_worker')
            ->where('mid','<>',UID)
            ->where('grab_sheet_end_time','>',time())
            ->where('status',1)
            ->where('id',$recruit_worker_id)
            ->find();
        if(!$recruit_worker){
            return json(['msg'=>'订单信息异常'],500);
        }

        //判断这个用户是否符合这条找工人的要求
        $member_info=Db::name('store_member')
            ->alias('m')
            ->join('worker_info w','w.mid=m.id')
            ->where('m.id',UID)
            ->field('w.work_type_ids,m.money,m.id,m.type')
            ->find();
        $worker_info=json_decode($recruit_worker['worker_info'],true);
        $is_match=false;
        $work_type=explode(',',$member_info['work_type_ids']);//工人工种数组
        //判断是否抢满了
        $worker_info_type=[];//订单工种分类
        foreach ($worker_info as $k=>$v){
            //$v['type'] $v['number']
            $worker_info_type[]=$v['type'];
            //查询这个工种已抢单人数
            $v['count']=Db::name('recruit_worker_grab_sheet')
                ->whereRaw('FIND_IN_SET('.$v['type'].',worker_type_ids)')
                ->count();
            $v['number']=$v['number']-$v['count'];
            if($v['number']>0&&in_array($v['type'],$work_type)){
                $is_match=true;
            }
        }
        if(!$is_match){
            return json(['msg'=>'您的技能与该订单需求不匹配，请入驻工人邦或完善您的技能'],500);
        }
        if($member_info['type']>0){
            //判断是否是超级会员
            $isSuper=MemberService::isSuper($member_info);
            if($isSuper) {
                $recruit_worker['point']=0;
            }else{
                //VIP
                //$recruit_worker['point']=$recruit_worker['point'];
            }
        }else{
            //$recruit_worker['point']=$recruit_worker['point'];
        }
        if($recruit_worker['point']>$member_info['money']){
            return json(['msg'=>'您的积分不足,请先充值'],500);
        }

        //判断是否抢过了
        $recruit_worker_grab_sheet=Db::name('recruit_worker_grab_sheet')
            ->where('mid',UID)
            ->where('recruit_worker_id',$recruit_worker_id)
            ->count();
        if($recruit_worker_grab_sheet>0){
            return json(['msg'=>'您已抢过该单了'],500);
        }

        $worker_type_ids=implode(',',array_intersect($work_type,$worker_info_type));
        //增加抢单信息
        Db::name('recruit_worker_grab_sheet')
            ->insert([
                'mid'=>UID,
                'recruit_worker_id'=>$recruit_worker_id,
                'worker_type_ids'=>$worker_type_ids,
                'status'=>0,
                'order_sn'=>DataService::createSequence(10,'RECRUIT_WORKER'),
                'addtime'=>time()
            ]);
        if($recruit_worker['point']>0){
            //扣除抢单者积分
            log_account_change(UID,-$recruit_worker['point'],0,'您于['.date('Y/m/d H:i:s').']参与找人抢单，扣除广告币',4);
            //分润
            MemberService::rebate(UID,$recruit_worker['point'],'您的下级用户['.UID.']于['.date('Y/m/d H:i:s').']参与找人抢单，您获得分润');
        }
        return json(['msg'=>'抢单成功'],200);
    }

    /**
     * 招工详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function detail(){
        //招工记录ID
        $recruit_worker_id=$this->request->get('recruit_worker_id');
        //查询找工人信息
        $recruit_worker=Db::name('recruit_worker')
            ->where('id',$recruit_worker_id)
            ->find();
        if(!$recruit_worker){
            return json(['msg'=>'数据错误'],500);
        }
        $recruit_worker['worker_info']=json_decode($recruit_worker['worker_info'],true);
        foreach ($recruit_worker['worker_info'] as $k=>&$v){
            $v['type']=getmodel($v['type'],'my_cate','title');
        }
        $recruit_worker['pay_type']=getmodel($recruit_worker['pay_type'],'my_cate','title');
        $recruit_worker['day_number']=($recruit_worker['end_time']-$recruit_worker['start_time'])/24/60/60;
        $recruit_worker['life_id_arr']=$recruit_worker['life_ids']?Db::name('my_cate')->where('id','in',$recruit_worker['life_ids'])
            ->column('title'):[];
        $recruit_worker['image_arr']=explode('|',$recruit_worker['image']);
        $recruit_worker['start_time']=date('Y/m/d',$recruit_worker['start_time']);
        $recruit_worker['end_time']=date('Y/m/d',$recruit_worker['end_time']);

        return json(['msg'=>'success','data'=>$recruit_worker]);
    }

    /**
     * 结束抢单
     * @return \think\response\Json
     */
    function end_grab_sheet(){
        //招工记录ID
        $recruit_worker_id=$this->request->get('recruit_worker_id');
        Db::name('recruit_worker')
            ->where('id',$recruit_worker_id)
            ->where('mid',UID)
            ->setField('status',1);
        return json(['msg'=>'已结束'],200);
    }

    /**
     * 删除抢单
     * @return \think\response\Json
     */
    function del(){
        //招工记录ID
        $recruit_worker_id=$this->request->get('recruit_worker_id');
        Db::transaction(function() use ($recruit_worker_id){
            Db::name('recruit_worker')
                ->where('id',$recruit_worker_id)
                ->where('mid',UID)
                ->delete();
            //删除抢单记录
            Db::name('recruit_worker_grab_sheet')
                ->where('recruit_worker_id',$recruit_worker_id)
                ->delete();
        });
        return json(['msg'=>'删除成功'],200);
    }

    /**
     * 选择工人
     * 已废弃
     * @return \think\response\Json
     */
    function choose_worker(){
        //$recruit_worker_id=$this->request->get('recruit_worker_id');
        $recruit_worker_grab_sheet_id=$this->request->get('grab_sheet_id');
        Db::name('recruit_worker_grab_sheet')
            //->where('recruit_worker_id',$recruit_worker_id)
            ->where('id',$recruit_worker_grab_sheet_id)
            ->where('status',0)
            ->setField('status',1);
        return json(['msg'=>'选择成功'],200);
    }
}